import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../theme/app_theme.dart';

class PeriodReminderSettingsScreen extends StatefulWidget {
  const PeriodReminderSettingsScreen({super.key});

  @override
  State<PeriodReminderSettingsScreen> createState() => _PeriodReminderSettingsScreenState();
}

class _PeriodReminderSettingsScreenState extends State<PeriodReminderSettingsScreen> {
  bool _isPeriodReminderEnabled = true;
  bool _isOvulationReminderEnabled = true;
  bool _isFertilityReminderEnabled = true;
  int _reminderDaysBeforePeriod = 3;
  TimeOfDay _periodReminderTime = const TimeOfDay(hour: 9, minute: 0);
  TimeOfDay _ovulationReminderTime = const TimeOfDay(hour: 9, minute: 0);
  TimeOfDay _fertilityReminderTime = const TimeOfDay(hour: 9, minute: 0);

  @override
  void initState() {
    super.initState();
    _loadSettings();
  }

  Future<void> _loadSettings() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _isPeriodReminderEnabled = prefs.getBool('periodReminderEnabled') ?? true;
      _isOvulationReminderEnabled = prefs.getBool('ovulationReminderEnabled') ?? true;
      _isFertilityReminderEnabled = prefs.getBool('fertilityReminderEnabled') ?? true;
      _reminderDaysBeforePeriod = prefs.getInt('reminderDaysBeforePeriod') ?? 3;
      
      
      final periodHour = prefs.getInt('periodReminderHour') ?? 9;
      final periodMinute = prefs.getInt('periodReminderMinute') ?? 0;
      _periodReminderTime = TimeOfDay(hour: periodHour, minute: periodMinute);
      
      final ovulationHour = prefs.getInt('ovulationReminderHour') ?? 9;
      final ovulationMinute = prefs.getInt('ovulationReminderMinute') ?? 0;
      _ovulationReminderTime = TimeOfDay(hour: ovulationHour, minute: ovulationMinute);
      
      final fertilityHour = prefs.getInt('fertilityReminderHour') ?? 9;
      final fertilityMinute = prefs.getInt('fertilityReminderMinute') ?? 0;
      _fertilityReminderTime = TimeOfDay(hour: fertilityHour, minute: fertilityMinute);
    });
  }

  Future<void> _saveSettings() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('periodReminderEnabled', _isPeriodReminderEnabled);
    await prefs.setBool('ovulationReminderEnabled', _isOvulationReminderEnabled);
    await prefs.setBool('fertilityReminderEnabled', _isFertilityReminderEnabled);
    await prefs.setInt('reminderDaysBeforePeriod', _reminderDaysBeforePeriod);
    
    
    await prefs.setInt('periodReminderHour', _periodReminderTime.hour);
    await prefs.setInt('periodReminderMinute', _periodReminderTime.minute);
    await prefs.setInt('ovulationReminderHour', _ovulationReminderTime.hour);
    await prefs.setInt('ovulationReminderMinute', _ovulationReminderTime.minute);
    await prefs.setInt('fertilityReminderHour', _fertilityReminderTime.hour);
    await prefs.setInt('fertilityReminderMinute', _fertilityReminderTime.minute);
    
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('设置已保存'),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  Future<void> _selectTime(BuildContext context, String type) async {
    TimeOfDay? picked;
    switch (type) {
      case 'period':
        picked = await showTimePicker(
          context: context,
          initialTime: _periodReminderTime,
          builder: (BuildContext context, Widget? child) {
            return Theme(
              data: ThemeData.light().copyWith(
                colorScheme: ColorScheme.light(primary: AppTheme.primaryColor),
              ),
              child: child!, 
            );
          },
        );
        if (picked != null) {
          setState(() => _periodReminderTime = picked!);
        }
        break;
      case 'ovulation':
        picked = await showTimePicker(
          context: context,
          initialTime: _ovulationReminderTime,
          builder: (BuildContext context, Widget? child) {
            return Theme(
              data: ThemeData.light().copyWith(
                colorScheme: ColorScheme.light(primary: AppTheme.primaryColor),
              ),
              child: child!, 
            );
          },
        );
        if (picked != null) {
          setState(() => _ovulationReminderTime = picked!);
        }
        break;
      case 'fertility':
        picked = await showTimePicker(
          context: context,
          initialTime: _fertilityReminderTime,
          builder: (BuildContext context, Widget? child) {
            return Theme(
              data: ThemeData.light().copyWith(
                colorScheme: ColorScheme.light(primary: AppTheme.primaryColor),
              ),
              child: child!, 
            );
          },
        );
        if (picked != null) {
          setState(() => _fertilityReminderTime = picked!);
        }
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: AppBar(
        backgroundColor: AppTheme.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
          color: AppTheme.textPrimary,
        ),
        title: Text('经期提醒设置', style: AppTheme.titleStyle),
        actions: [
          TextButton(
            onPressed: _saveSettings,
            child: Text('保存', style: TextStyle(color: AppTheme.primaryColor)),
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              
              Container(
                margin: const EdgeInsets.only(bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('经期提醒', style: AppTheme.subtitleStyle),
                    const SizedBox(height: 12),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('开启提醒', style: AppTheme.bodyStyle),
                        Switch(
                          value: _isPeriodReminderEnabled,
                          onChanged: (value) {
                            setState(() => _isPeriodReminderEnabled = value);
                          },
                          activeThumbColor: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    if (_isPeriodReminderEnabled)
                      Column(
                        children: [
                          const SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('提前提醒天数', style: AppTheme.bodyStyle),
                              DropdownButton<int>(
                                value: _reminderDaysBeforePeriod,
                                items: const [
                                  DropdownMenuItem(value: 1, child: Text('1天')),
                                  DropdownMenuItem(value: 2, child: Text('2天')),
                                  DropdownMenuItem(value: 3, child: Text('3天')),
                                  DropdownMenuItem(value: 5, child: Text('5天')),
                                  DropdownMenuItem(value: 7, child: Text('7天')),
                                ],
                                onChanged: (value) {
                                  setState(() => _reminderDaysBeforePeriod = value!);
                                },
                                style: AppTheme.bodyStyle,
                                icon: Icon(Icons.arrow_drop_down, color: AppTheme.textSecondary),
                              ),
                            ],
                          ),
                          const SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('提醒时间', style: AppTheme.bodyStyle),
                              TextButton(
                                onPressed: () => _selectTime(context, 'period'),
                                child: Text(
                                  _periodReminderTime.format(context),
                                  style: TextStyle(color: AppTheme.primaryColor),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                  ],
                ),
              ),

              
              Container(
                margin: const EdgeInsets.only(bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('排卵期提醒', style: AppTheme.subtitleStyle),
                    const SizedBox(height: 12),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('开启提醒', style: AppTheme.bodyStyle),
                        Switch(
                          value: _isOvulationReminderEnabled,
                          onChanged: (value) {
                            setState(() => _isOvulationReminderEnabled = value);
                          },
                          activeThumbColor: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    if (_isOvulationReminderEnabled)
                      Column(
                        children: [
                          const SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('提醒时间', style: AppTheme.bodyStyle),
                              TextButton(
                                onPressed: () => _selectTime(context, 'ovulation'),
                                child: Text(
                                  _ovulationReminderTime.format(context),
                                  style: TextStyle(color: AppTheme.primaryColor),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                  ],
                ),
              ),

              
              Container(
                margin: const EdgeInsets.only(bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('生育窗口提醒', style: AppTheme.subtitleStyle),
                    const SizedBox(height: 12),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('开启提醒', style: AppTheme.bodyStyle),
                        Switch(
                          value: _isFertilityReminderEnabled,
                          onChanged: (value) {
                            setState(() => _isFertilityReminderEnabled = value);
                          },
                          activeThumbColor: AppTheme.primaryColor,
                        ),
                      ],
                    ),
                    if (_isFertilityReminderEnabled)
                      Column(
                        children: [
                          const SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('提醒时间', style: AppTheme.bodyStyle),
                              TextButton(
                                onPressed: () => _selectTime(context, 'fertility'),
                                child: Text(
                                  _fertilityReminderTime.format(context),
                                  style: TextStyle(color: AppTheme.primaryColor),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                  ],
                ),
              ),

              
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: AppTheme.white,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('使用说明', style: AppTheme.subtitleStyle),
                    const SizedBox(height: 8),
                    Text(
                      '• 经期提醒：在预测的经期开始前指定天数提醒您\n' 
                      '• 排卵期提醒：在预测的排卵日当天提醒您\n' 
                      '• 生育窗口提醒：在预测的生育窗口期内每天提醒您',
                      style: AppTheme.bodyStyle,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
